<template>
  <view class="avatar-main" :class="{ column: column }">
    <view
      class="avatar-container"
      :style="{
        width: column ? '400rpx' : sizerPx + 'rpx',
        height: column ? '200rpx' : sizerPx + 'rpx',
      }"
      @click="handleClick"
    >
      <!-- 头像图片 -->
      <image
        :src="src || defaultSrc"
        class="avatar-image"
        :class="{ round: column ? false : round }"
        mode="aspectFill"
        @load="onLoad"
      />

      <!-- 在线状态角标（可选） -->
      <view v-if="showBadge" class="status-badge" :class="[`status-${status}`]"></view>

      <!-- <u-icon :name="loadingIcon" :color="iconColor" :size="iconSize" class="placeholder-icon" /> -->
    </view>
    <view @tap="uploadAvatar">{{ title }}</view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

import defaultSrcImg from '@/static/img/12.png'

// ==================== Props 定义 ====================
const props = defineProps({
  // 头像图片地址
  uploadUrl: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  // 头像图片地址
  src: {
    type: String,
    default: '',
  },
  // 是否圆形
  round: {
    type: Boolean,
    default: true,
  },
  column: {
    type: Boolean,
    default: false,
  },
  // 尺寸大小（支持数字或 small/normal/large）
  size: {
    type: [Number, String],
    default: 80,
  },
  // 点击是否可预览
  preview: {
    type: Boolean,
    default: true,
  },
  // 显示状态角标（在线、离线等）
  showBadge: {
    type: Boolean,
    default: false,
  },
  // 状态类型：online, offline, busy
  status: {
    type: String,
    validator: (value) => ['online', 'offline', 'busy'].includes(value),
    default: 'offline',
  },
  // 默认头像 URL
  defaultSrc: {
    type: String,
    default: defaultSrcImg, // 建议放在 static 目录
  },
  // 是否显示加载图标
  showLoading: {
    type: Boolean,
    default: true,
  },
  // 是否显示错误图标
  showError: {
    type: Boolean,
    default: true,
  },
})

// ==================== 事件 emit ====================
const emit = defineEmits(['click', 'upload', 'load', 'error'])

// ==================== 内部状态 ====================
const loaded = ref(false)
const isError = ref(false)
const loadingIcon = ref('account') // uView 图标名
const iconColor = ref('#c0c4cc')
const iconSize = computed(() => Math.max(props.size * 0.6, 20))

// ==================== 计算属性：解析 size ====================
const sizerPx = computed(() => {
  if (typeof props.size === 'number') return props.size
  const sizes = { small: 80, normal: 120, large: 200 }
  return sizes[props.size] || 80
})

// ==================== 事件处理 ====================
const onLoad = (e) => {
  loaded.value = true
  isError.value = false
  emit('load', e)
}

const onError = (e) => {
  loaded.value = false
  isError.value = true
  emit('error', e)
}

const uploadAvatar = () => {
  // 调用拍照/选择图片
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      // 本地路径
      const { tempFilePath } = res.tempFiles[0]
      // 文件上传
      uni.uploadFile({
        url: props.uploadUrl || '/oss/file/upload',
        name: 'file', // 后端数据字段名
        filePath: tempFilePath, // 新头像
        success: (res) => {
          // 判断状态码是否上传成功
          if (res.statusCode === 200) {
            emit('upload', JSON.parse(res.data).data)
            // // 当前页面更新头像
            // form.value.images = [...form.value.images, url]
            // // 更新 Store 头像
            // memberStore.userInfo!.avatarUrl = url
            uni.showToast({ icon: 'success', title: '更新成功' })
          } else {
            uni.showToast({ icon: 'error', title: '出现错误' })
          }
        },
      })
    },
  })
}

const handleClick = () => {
  // emit('click')
  if (props.preview && props.src) {
    uni.previewImage({
      urls: [props.src],
      current: 0,
    })
  }
}
</script>

<style scoped lang="scss">
.avatar-main {
  display: flex;
  align-items: center;
  &.column {
    justify-content: center;
    flex-direction: column;
    .avatar-container {
      width: 400rpx;
      height: 200rpx;
      margin-right: 0rpx;
      margin-bottom: 20rpx;
    }
  }
}
.avatar-container {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.round {
  border-radius: 50%;
}

.status-badge {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  border: 2px solid #fff;

  &.status-online {
    background-color: #4cd964; /* 在线 */
  }

  &.status-offline {
    background-color: #ccc; /* 离线 */
  }

  &.status-busy {
    background-color: #f00; /* 忙碌 */
  }
}

.placeholder-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
